package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.entity.WmNewsMaterial;
import com.heima.wemedia.service.WmNewsMaterialService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class WmNewsMaterialServiceImpl extends ServiceImpl<WmNewsMaterialMapper, WmNewsMaterial> implements WmNewsMaterialService {
   /**
     * 根据文章id 删除中间表数据
     * @param id
     */
    @Override
    public void deleteByNewsId(Integer id) {
        QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WmNewsMaterial::getNewsId,id);
        boolean b = remove(queryWrapper);
    }
   /**
     * 批量保存文章素材中间表
     * @param materialIds
     * @param wmNewsId
     * @param type
     */
    @Override
    public void saveInfoBatch(List<Integer> materialIds, Integer wmNewsId, int type) {
		if(CollectionUtils.isEmpty(materialIds)){
            return ;
        }
        List<WmNewsMaterial> wmNewsMaterialList = new ArrayList<>();
        for (Integer materialId : materialIds) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(materialId);
            wmNewsMaterial.setNewsId(wmNewsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterialList.add(wmNewsMaterial);
        }
        if(CollectionUtils.isEmpty(wmNewsMaterialList)){
            return ;
        }
        boolean b = saveBatch(wmNewsMaterialList);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}